const WebSocket = require('ws');
const db = require('../config/db');
const Friend = require('../models/friendModel');
const User = require('../models/userModel');
const WebSocketConnection = require('../models/websocketModel');

// 全局 Map 记录用户连接
const userConnections = new Map();

const setupWebSocket = (server) => {
  const wss = new WebSocket.Server({ server });

  wss.on('connection', (ws, req) => {
    // 从 URL 参数中获取 userId
    const userId = new URL(req.url, `ws://${req.headers.host}`).searchParams.get('userId');
    if (!userId) {
      console.error('No userId provided in WebSocket connection');
      ws.close(); // 关闭连接
      return;
    }

    console.log(`User ${userId} connected`);

    // 将连接记录到全局 Map
    userConnections.set(userId, ws);
    console.log('userConnections=',userConnections);
    console.log(`User ${userId} connection stored in memory`);

    // 处理消息
    ws.on('message', async (message) => {
      const data = JSON.parse(message);

      if (data.type === 'login') {
        const { userId } = data;
        console.log(`User ${userId} logged in`);

        // 更新用户状态为 online
        User.updateStatus(userId, 'online', (err) => {
          if (err) {
            console.error(`Error updating status for user ${userId}:`, err);
          } else {
            console.log(`User ${userId} status updated to online`);
          }
        });

        return;
      }

      const { senderId, receiverId, content } = data;
      console.log(`Message received from ${senderId} to ${receiverId}: ${content}`);

      // 更新发送者的最后活跃时间
      User.updateLastActive(senderId, (err) => {
        if (err) {
          console.error('Error updating last active:', err);
        } else {
          console.log(`User ${senderId} last active time updated`);
        }
      });

      // 验证是否为好友
      Friend.areFriends(senderId, receiverId, (err, result) => {
        if (err) {
          console.error('Error checking friendship:', err);
          return ws.send(JSON.stringify({ error: 'Database error' }));
        }
        if (!result) {
          console.log(`User ${senderId} tried to send message to non-friend ${receiverId}`);
          return ws.send(JSON.stringify({ error: 'You can only chat with friends' }));
        }

        // 保存消息到数据库
        db.run(
          'INSERT INTO messages (sender_id, receiver_id, message) VALUES (?, ?, ?)',
          [senderId, receiverId, content],
          (err) => {
            if (err) {
              console.error('Error saving message:', err);
            } else {
              console.log('Message saved to database');
            }
          }
        );

        // 从全局 Map 中查找接收者的 WebSocket 连接
        const receiverWs = userConnections.get(receiverId);
        if (receiverWs) {
          receiverWs.send(JSON.stringify({
            senderId: senderId,
            receiverId,
            content,
            timestamp: new Date().toISOString()
          }));
          console.log(`Message sent to user ${receiverId}`);
        } else {
          console.error(`Receiver ${receiverId} not connected`);
        }
      });
    });

    // 用户断开连接时移除记录
    ws.on('close', () => {
      console.log(`User ${userId} disconnected`);

      // 从全局 Map 中移除连接
      userConnections.delete(userId);
      console.log(`User ${userId} connection removed from memory`);
    });
  });
};

module.exports = setupWebSocket; 